/*
 * @lc app=leetcode.cn id=547 lang=typescript
 *
 * [547] 省份数量
 */

// @lc code=start
// 并查集模板
class UnionFind {
  parent: number[];
  size: number[];
  count: number;
  constructor(n: number = 0) {
    this.parent = new Array(n).fill(0).map((_, i) => i);
    this.size = new Array(n).fill(1);
    this.count = n;
  }

  find(x: number): number {
    if (x === this.parent[x]) return x;
    this.parent[x] = this.find(this.parent[x]);
    return this.parent[x];
  }

  union(x: number, y: number) {
    let rx = this.find(x);
    let ry = this.find(y);
    if (rx === ry) return;
    if (this.size[rx] > this.size[ry]) {
      [rx, ry] = [ry, rx];
    }
    this.parent[rx] = ry;
    this.size[ry] += this.size[rx];
    this.count--;
  }
}

function findCircleNum(isConnected: number[][]): number {
  const size = isConnected.length;
  const unionFind = new UnionFind(size);

  for (let i = 0; i < size; i++) {
    let item = isConnected[i];
    for (let j = 0; j < item.length; j++) {
      if (isConnected[i][j]) {
        unionFind.union(i, j);
      }
    }
  }
  return unionFind.count;
}
// @lc code=end
